<template>
  <div class="login-container">
    <div class="login-card-wrapper">
      <el-card class="login-card">
        <div class="login-header">
          <h2>欢迎登录</h2>
          <p class="subtitle">请输入您的账号和密码</p>
        </div>

        <el-form
            ref="loginFormRef"
            :model="loginForm"
            :rules="rules"
            label-position="top"
            status-icon
        >
          <el-form-item prop="username">
            <el-input
                v-model="loginForm.username"
                :prefix-icon="User"
                placeholder="请输入账号"
                clearable
            />
          </el-form-item>

          <el-form-item prop="password">
            <el-input
                v-model="loginForm.password"
                :prefix-icon="Lock"
                type="password"
                placeholder="请输入密码"
                show-password
            />
          </el-form-item>

          <div class="remember-forgot">
            <el-checkbox v-model="loginForm.remember">记住我</el-checkbox>
            <el-link type="primary" :underline="false">忘记密码?</el-link>
          </div>

          <el-form-item>
            <el-button
                type="primary"
                :loading="loading"
                class="login-button"
                @click="handleLogin"
            >
              登录
            </el-button>
          </el-form-item>
        </el-form>

        <!--        <div class="login-footer">-->
        <!--          <p>还没有账号? <el-link type="primary" :underline="false">立即注册</el-link></p>-->
        <!--        </div>-->
        <!--        第一次修改-->
        <div class="login-footer">
          <p>还没有账号? <el-link type="primary" :underline="false" @click="goToRegister">立即注册</el-link></p>
        </div>

      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { User, Lock } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import md5 from 'md5'
import {userLogin} from "@/api/login/login.js";

const router = useRouter()
const loading = ref(false)
const loginForm = reactive({
  username: '', // 这里保持username字段名不变，但在请求时可以映射为account
  password: '',
  remember: false
})

const loginFormRef = ref(null)

const rules = {
  username: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { pattern: /^\d{11}$/, message: '账号必须是11位数字', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ]
}

const handleLogin = () => {
  loginFormRef.value?.validate(async (valid) => {
    if (valid) {
      loading.value = true

      try {
        // 对密码进行MD5加密
        const encryptedPassword = md5(loginForm.password)

        // 准备发送到后端的数据
        const loginData = {
          account: loginForm.username, // 将username映射为account
          password: encryptedPassword
        }

        // 发送登录请求到后端
        const response = await userLogin(loginData)

        // 处理后端响应
        if (response.data.code === 200) {
          // 登录成功
          ElMessage.success('登录成功')

          // 存储用户信息和token
          localStorage.setItem('token', response.data.data.token || 'default-token')
          localStorage.setItem('userRole', response.data.data.role)
          localStorage.setItem('userName', response.data.data.account || loginForm.username)

          // 根据用户角色重定向到不同的页面
          switch (response.data.data.role) {
            case 'admin':
              router.push('/admin')
              break
            case 'worker':
              router.push('/worker')
              break
            case 'client':
              router.push('/client')
              break
            default:
              router.push('/login')
          }
        } else if(response.data.code === 401){
          // 登录失败
          ElMessage.error(response.data.message || '登录失败，用户名或密码错误')
        }
      } catch (error) {
        console.error('登录请求失败:', error)
        //ElMessage.error(error.response?.data?.message || '登录失败，请稍后再试')
      } finally {
        loading.value = false
      }
    } else {
      return false
    }
  })
}

const goToRegister = () => {
  router.push('/register')
}


// const handleLogin = () => {
//   loginFormRef.value?.validate((valid) => {
//     if (valid) {
//       loading.value = true
//
//       // 这里替换为您的登录API调用
//       setTimeout(() => {
//         loading.value = false
//         // 存储token
//         localStorage.setItem('token', 'your-auth-token')
//         ElMessage.success('登录成功')
//         router.push('/home')
//       }, 1500)
//     } else {
//       return false
//     }
//   })
// }

</script>

<style scoped>
.login-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
  background-image: url('/background.png');  /* 修改为使用背景图片 */
  background-size: cover;  /* 确保图片覆盖整个容器 */
  background-position: center;  /* 图片居中 */
  background-repeat: no-repeat;  /* 不重复图片 */
}

.login-card-wrapper {
  width: 400px;
  max-width: 90%;
}

.login-card {
  width: 100%;
  border-radius: 8px;
  box-shadow: 0 12px 24px rgba(0, 0, 0, 0.15);
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-header h2 {
  font-size: 28px;
  color: #303133;
  margin-bottom: 8px;
}

.subtitle {
  color: #606266;
  font-size: 14px;
}

.login-button {
  width: 100%;
  padding: 12px 0;
  border-radius: 4px;
  margin-top: 10px;
}

.remember-forgot {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.login-footer {
  margin-top: 20px;
  text-align: center;
  color: #606266;
  font-size: 14px;
}
</style>
